<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

class music extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'music:send {action}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'i微影音乐脚本';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    /*public function __construct()
    {
        parent::__construct();

    }*/

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // 获取参数，调用方法
        $action = $this->argument('action');
        $this->$action();
    }

    /*
     * 音乐排序
     * */
    private function music_sort()
    {
        $task_key = config('feild.redis.task.music_sort.key');
        $max_lock_time = config('feild.redis.task.music_sort.max_lock_time');
        if(!empty(Redis::get($task_key)))
            return '任务正在执行，请稍后';
        Redis::setex($task_key, $max_lock_time, 1);

        $mudic_type = \App\Models\Music::select('category')->groupby('category')->get();
        foreach ($mudic_type as $value){
            $category = $value->category;
            $this->music_sort_rule($category);
        }
        Redis::del($task_key);
    }

    /*
     * 排序规则
     * 通过每个类型排序
     * 排序规则：1.取出未锁定排序位置的列表  2.重组数组 3.取出锁定排序的列表，遍历，通过排序指定插入到重组数组中
     * */
    private function music_sort_rule($category)
    {
        $category_redis_key = config('feild.redis.music_sort.key').$category;
        $category_max_lock_time = config('feild.redis.music_sort.lock_time');
        Redis::setex($category_redis_key, $category_max_lock_time, 1);

        // 重组数组
        $arr = [];
        // 通过应用排序取出
        $list = \App\Models\Music::select(['id', 'sort', 'number'])->where([['category', '=', $category], ['status', '=', '0'], ['is_delete', '=', '0'], ['flag', '!=', 1]])->orderby('number', 'desc')->orderby('sort', 'asc')->get();
        foreach ($list as $v)
            $arr[] = ['id'=>$v->id, 'sort'=>$v->sort, 'number'=>$v->number];

        // 取出固定排序音乐 flag = 1 是锁定的排序，插入锁定位置
        $flag_list = \App\Models\Music::select(['id', 'sort'])->where([['category', '=', $category], ['status', '=', '0'], ['is_delete', '=', '0'], ['flag', '=', 1]])->orderby('sort', 'asc')->get();
        foreach ($flag_list as $value){
            $sort = ($value->sort-1);
            array_splice($arr, $sort, 0, [['id'=>$value->id, 'sort'=>$value->sort]]); // 插入到位置3且删除0个
        }

        $i = 0;
        foreach ($arr as $update_value){
            $i++;
            \App\Models\Music::where([['id', '=', $update_value['id']]])->update(['sort'=>$i]);
        }
        Redis::del($category_redis_key);
    }


}
